package com.ujson.base.common.task;

import com.ujson.base.common.utils.LogUtil;
import com.ujson.base.common.utils.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * <h3>ujson-parent</h3>
 * <p>异步任务</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-28 21:11
 */
@Slf4j
public class AsyncTask {

    public static <T> CompletableFuture<T> addTask(Supplier<T> supplier) {
        CompletableFuture<T> cf =  CompletableFuture.supplyAsync(supplier, ThreadUtil.getIoIntenseTargetThreadPool());
        cf.exceptionally(ex -> {
            LogUtil.error(log, "async execute error with return.", ex);
            return null;
        });

        return cf;
    }

    public static void addTask(Runnable runnable) {
        CompletableFuture<Void> cf = CompletableFuture.runAsync(runnable, ThreadUtil.getIoIntenseTargetThreadPool());
        cf.exceptionally(ex ->{
            LogUtil.error(log, "async execute error with return Void.", ex);
            return null;
        });
    }
}
